from rest_framework import serializers
from apps.core.models import Template, ProcessingTask, UploadedFile


class ProcessingRequestSerializer(serializers.Serializer):
    """处理请求序列化器"""
    
    template_id = serializers.IntegerField(
        help_text="模板ID"
    )
    
    source_file_ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="源文件ID列表"
    )
    
    task_name = serializers.CharField(
        max_length=200,
        required=False,
        help_text="任务名称"
    )
    
    options = serializers.DictField(
        required=False,
        help_text="处理选项"
    )
    
    def validate_template_id(self, value):
        """验证模板ID"""
        try:
            template = Template.objects.get(id=value, is_active=True)
            return value
        except Template.DoesNotExist:
            raise serializers.ValidationError("模板不存在或未激活")
    
    def validate_source_file_ids(self, value):
        """验证源文件ID列表"""
        if not value:
            raise serializers.ValidationError("至少需要一个源文件")
        
        if len(value) > 20:
            raise serializers.ValidationError("一次最多处理20个文件")
        
        # 检查文件是否存在
        existing_files = UploadedFile.objects.filter(
            id__in=value,
            file_type='source'
        ).count()
        
        if existing_files != len(value):
            raise serializers.ValidationError("部分源文件不存在")
        
        return value
    
    def validate_options(self, value):
        """验证处理选项"""
        if not value:
            return {}
        
        allowed_keys = ['group_by', 'output_format', 'merge_sheets', 'custom_rules']
        
        for key in value.keys():
            if key not in allowed_keys:
                raise serializers.ValidationError(f"不支持的选项: {key}")
        
        # 验证group_by选项
        if 'group_by' in value:
            allowed_group_by = ['POL', 'SS_Number', 'Number', 'Shipper']
            if value['group_by'] not in allowed_group_by:
                raise serializers.ValidationError(
                    f"group_by必须是以下值之一: {', '.join(allowed_group_by)}"
                )
        
        # 验证output_format选项
        if 'output_format' in value:
            allowed_formats = ['xlsx', 'xls']
            if value['output_format'] not in allowed_formats:
                raise serializers.ValidationError(
                    f"output_format必须是以下值之一: {', '.join(allowed_formats)}"
                )
        
        return value


class ProcessingResultSerializer(serializers.Serializer):
    """处理结果序列化器"""
    
    success = serializers.BooleanField(
        help_text="是否成功"
    )
    
    task_id = serializers.IntegerField(
        required=False,
        help_text="任务ID"
    )
    
    message = serializers.CharField(
        required=False,
        help_text="处理消息"
    )
    
    error = serializers.CharField(
        required=False,
        help_text="错误信息"
    )
    
    generated_files = serializers.ListField(
        child=serializers.CharField(),
        required=False,
        help_text="生成的文件列表"
    )
    
    zip_file = serializers.CharField(
        required=False,
        help_text="压缩包文件名"
    )
    
    total_files = serializers.IntegerField(
        required=False,
        help_text="生成文件总数"
    )


class TaskStatusSerializer(serializers.ModelSerializer):
    """任务状态序列化器"""
    
    template_name = serializers.CharField(
        source='template.name',
        read_only=True,
        help_text="模板名称"
    )
    
    status_display = serializers.CharField(
        source='get_status_display',
        read_only=True,
        help_text="状态显示名称"
    )
    
    progress_percentage = serializers.SerializerMethodField(
        help_text="进度百分比"
    )
    
    duration = serializers.SerializerMethodField(
        help_text="处理耗时（秒）"
    )
    
    result_file_count = serializers.SerializerMethodField(
        help_text="结果文件数量"
    )
    
    class Meta:
        model = ProcessingTask
        fields = [
            'id', 'task_name', 'template_name', 'status', 'status_display',
            'progress', 'progress_percentage', 'created_at', 'started_at',
            'completed_at', 'duration', 'error_message', 'result_files',
            'result_file_count'
        ]
        read_only_fields = ['id', 'created_at', 'started_at', 'completed_at']
    
    def get_progress_percentage(self, obj):
        """获取进度百分比"""
        return f"{obj.progress}%"
    
    def get_duration(self, obj):
        """获取处理耗时"""
        if obj.started_at and obj.completed_at:
            duration = obj.completed_at - obj.started_at
            return duration.total_seconds()
        return None
    
    def get_result_file_count(self, obj):
        """获取结果文件数量"""
        if obj.result_files and 'files' in obj.result_files:
            return len(obj.result_files['files'])
        return 0


class FilePreviewSerializer(serializers.Serializer):
    """文件预览序列化器"""
    
    file_id = serializers.IntegerField(
        help_text="文件ID"
    )
    
    max_rows = serializers.IntegerField(
        default=10,
        min_value=1,
        max_value=100,
        help_text="最大预览行数"
    )
    
    def validate_file_id(self, value):
        """验证文件ID"""
        try:
            file_obj = UploadedFile.objects.get(id=value)
            return value
        except UploadedFile.DoesNotExist:
            raise serializers.ValidationError("文件不存在")


class FileInfoSerializer(serializers.Serializer):
    """文件信息序列化器"""
    
    file_path = serializers.CharField(
        help_text="文件路径"
    )
    
    file_name = serializers.CharField(
        help_text="文件名"
    )
    
    file_size = serializers.IntegerField(
        help_text="文件大小（字节）"
    )
    
    file_ext = serializers.CharField(
        help_text="文件扩展名"
    )
    
    modified_time = serializers.DateTimeField(
        help_text="修改时间"
    )
    
    is_excel = serializers.BooleanField(
        help_text="是否为Excel文件"
    )
    
    is_csv = serializers.BooleanField(
        help_text="是否为CSV文件"
    )
    
    sheet_names = serializers.ListField(
        child=serializers.CharField(),
        required=False,
        help_text="工作表名称列表（Excel文件）"
    )
    
    sheet_count = serializers.IntegerField(
        required=False,
        help_text="工作表数量（Excel文件）"
    )
    
    columns = serializers.ListField(
        child=serializers.CharField(),
        required=False,
        help_text="列名列表"
    )
    
    column_count = serializers.IntegerField(
        required=False,
        help_text="列数量"
    )
    
    error = serializers.CharField(
        required=False,
        help_text="错误信息"
    )


class FilePreviewDataSerializer(serializers.Serializer):
    """文件预览数据序列化器"""
    
    columns = serializers.ListField(
        child=serializers.CharField(),
        help_text="列名列表"
    )
    
    data = serializers.ListField(
        child=serializers.DictField(),
        help_text="数据行列表"
    )
    
    total_rows = serializers.IntegerField(
        help_text="总行数"
    )
    
    total_columns = serializers.IntegerField(
        help_text="总列数"
    )
    
    error = serializers.CharField(
        required=False,
        help_text="错误信息"
    )


class TemplateValidationSerializer(serializers.Serializer):
    """模板验证序列化器"""
    
    template_id = serializers.IntegerField(
        help_text="模板ID"
    )
    
    def validate_template_id(self, value):
        """验证模板ID"""
        try:
            template = Template.objects.get(id=value)
            return value
        except Template.DoesNotExist:
            raise serializers.ValidationError("模板不存在")


class TemplateValidationResultSerializer(serializers.Serializer):
    """模板验证结果序列化器"""
    
    is_valid = serializers.BooleanField(
        help_text="是否有效"
    )
    
    message = serializers.CharField(
        help_text="验证消息"
    )
    
    config_summary = serializers.DictField(
        help_text="配置摘要"
    )
    
    errors = serializers.ListField(
        child=serializers.CharField(),
        required=False,
        help_text="错误列表"
    )
    
    warnings = serializers.ListField(
        child=serializers.CharField(),
        required=False,
        help_text="警告列表"
    )


class ProcessingOptionsSerializer(serializers.Serializer):
    """处理选项序列化器"""
    
    group_by = serializers.ChoiceField(
        choices=['POL', 'SS_Number', 'Number', 'Shipper'],
        required=False,
        help_text="分组依据"
    )
    
    output_format = serializers.ChoiceField(
        choices=['xlsx', 'xls'],
        default='xlsx',
        help_text="输出格式"
    )
    
    merge_sheets = serializers.BooleanField(
        default=False,
        help_text="是否合并工作表"
    )
    
    custom_rules = serializers.DictField(
        required=False,
        help_text="自定义规则"
    )
    
    include_summary = serializers.BooleanField(
        default=True,
        help_text="是否包含汇总信息"
    )
    
    compress_output = serializers.BooleanField(
        default=True,
        help_text="是否压缩输出"
    )


class BatchProcessingSerializer(serializers.Serializer):
    """批量处理序列化器"""
    
    tasks = serializers.ListField(
        child=ProcessingRequestSerializer(),
        help_text="任务列表"
    )
    
    batch_name = serializers.CharField(
        max_length=200,
        required=False,
        help_text="批次名称"
    )
    
    parallel = serializers.BooleanField(
        default=False,
        help_text="是否并行处理"
    )
    
    def validate_tasks(self, value):
        """验证任务列表"""
        if not value:
            raise serializers.ValidationError("至少需要一个任务")
        
        if len(value) > 10:
            raise serializers.ValidationError("一次最多处理10个任务")
        
        return value